package com.tianji.learning.listener;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.learning.domain.dto.SignMessage;
import com.tianji.learning.enums.PointsRecordType;
import com.tianji.learning.service.IInteractionReplyService;
import com.tianji.learning.service.IPointsRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import static com.tianji.common.constants.MqConstants.Exchange.LEARNING_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.SIGN_IN;
import static com.tianji.common.constants.MqConstants.Key.WRITE_REPLY;
import static com.tianji.common.constants.MqConstants.Queue.QA_POINTS_QUEUE;
import static com.tianji.common.constants.MqConstants.Queue.SING_POINTS_QUEUE;

@Slf4j
@Component
@RequiredArgsConstructor
public class LearningPointsRecordListener {
    private final IPointsRecordService recordService;

    /**
     * 监听签到添加积分消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = SING_POINTS_QUEUE, durable = "true"),
            exchange = @Exchange(name = LEARNING_EXCHANGE, type = "topic"),
            key = SIGN_IN
    ))
    public void addSignPoints(SignMessage signMessage) {
        log.info("用户{}签到成功，开始添加积分", signMessage);
        if (ObjectUtil.isEmpty(signMessage) || ObjectUtil.isEmpty(signMessage.getUserId()) || ObjectUtil.isEmpty(signMessage.getPoints())){
            log.error("签到消息格式异常，消息{}",signMessage);
        }
        recordService.addPoints(signMessage.getUserId(), signMessage.getPoints(), PointsRecordType.SIGN);
    }

    /**
     * 监听写回答添加积分消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = QA_POINTS_QUEUE, durable = "true"),
            exchange = @Exchange(name = LEARNING_EXCHANGE, type = "topic"),
            key = WRITE_REPLY
    ))
    public void addSignPoints(Long userId) {
        log.info("用户{}回答，开始添加积分", userId);
        if (ObjectUtil.isEmpty(userId) ){
            log.error("写回复消息格式异常，消息{}",userId);
        }
        recordService.addPoints(userId,5, PointsRecordType.QA);
    }
}
